/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.tianruan.dc.modules.generator.controller;

import com.tianruan.dc.modules.generator.service.SysGeneratorService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 代码生成器
 */
@Controller
@RequestMapping("/api/sys/generator")
public class SysGeneratorController {
	@Autowired
	private SysGeneratorService sysGeneratorService;
	
//	/**
//	 * 列表
//	 */
//	@ResponseBody
//	@RequestMapping("/list")
//	public R list(@RequestParam Map<String, Object> params){
//		PageUtils pageUtil = sysGeneratorService.queryList(new Query(params));
//
//		return R.ok().put("page", pageUtil);
//	}

	/**
	 * 生成代码
	 */
	@PreAuthorize("hasAnyAuthority('sys:super:admin')")
	@RequestMapping("/code")
	public void code(@RequestParam(value = "moduleName", required = false) String moduleName,
					 @RequestParam(value = "author", required = false) String author,
					 @RequestParam(value = "email", required = false) String email,
					 @RequestParam("tables") String tables,
					 @RequestParam("tablePrefixes") String tablePrefixes,
					 HttpServletResponse response) throws IOException{
		// 生成代码
		byte[] data = sysGeneratorService.generatorCode(moduleName, author, email, tables.split(","), tablePrefixes.split(","));

		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"generatorCode.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}
}
